package com.edward.mvpdemo.view;

import android.os.Bundle;
import android.support.v7.app.AppCompatActivity;
import android.view.View;
import android.widget.ArrayAdapter;
import android.widget.Button;
import android.widget.ListView;
import android.widget.ProgressBar;
import android.widget.TextView;
import android.widget.Toast;

import com.edward.mvpdemo.R;
import com.edward.mvpdemo.presenter.IDataPresenter;
import com.edward.mvpdemo.presenter.IDataPresenterImpl;

import java.util.ArrayList;
import java.util.List;

public class MainActivity extends AppCompatActivity implements IMainView {
    private Button btn_load;
    private ListView lv_data;
    private TextView tv_error;
    private ProgressBar pb_loading;

    private ArrayAdapter adapter;


    private List<String> mData;

    private IDataPresenter dataPresenter;

    private int start = 1;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);
        initView();

        dataPresenter = new IDataPresenterImpl(this);
    }

    private void initView() {
        btn_load = (Button) findViewById(R.id.btn_load);
        lv_data = (ListView) findViewById(R.id.lv_main);
        tv_error = (TextView) findViewById(R.id.tv_error);
        pb_loading = (ProgressBar) findViewById(R.id.pb_loading);

        mData = new ArrayList<>();
        adapter = new ArrayAdapter(this, R.layout.item_layout, mData);
        lv_data.setAdapter(adapter);

        btn_load.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                dataPresenter.getData(start);
            }
        });
    }

    public void setmData(List<String> data) {
        mData.addAll(data);
        adapter.notifyDataSetChanged();
    }

    @Override
    public void showError(String error) {
        lv_data.setVisibility(View.INVISIBLE);
        tv_error.setVisibility(View.VISIBLE);
        pb_loading.setVisibility(View.INVISIBLE);
        tv_error.setText(error);
    }

    @Override
    public void showSuccess() {
        start += 20;
        lv_data.setVisibility(View.VISIBLE);
        tv_error.setVisibility(View.INVISIBLE);
        pb_loading.setVisibility(View.INVISIBLE);
    }

    @Override
    public void showLoading() {
        Toast.makeText(this, "正在加载数据", Toast.LENGTH_SHORT).show();
        pb_loading.setVisibility(View.VISIBLE);
        lv_data.setVisibility(View.INVISIBLE);
        tv_error.setVisibility(View.INVISIBLE);
    }
}
